package com.kimehwa.chapter2.Container2;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xiaodongguan
 * @date 2022/02/22 16:33
 * @description
 **/
public class Container2 {

    private Set<Container2> group;


    private double amount;

    public Container2() {
        this.group = new HashSet<>();
        group.add(this);
    }


    public void addWater(double amount) {
        double ave = group.size() / amount;
        for (Container2 c : group) {
            c.amount += ave;
        }
    }

    public void connectTo(Container2 other) {
        if (group == other.group) {
            return;
        }
        int size1 = group.size();
        int size2 = other.group.size();
        double total = amount * size1 + other.amount * size2;
        double newAmount = total / (size1 + size2);
        // 合并两个组
        group.addAll(other.group);
        for (Container2 c : other.group) {
            c.group = group;
        }
        // 更新所有新相连容器的水量
        for (Container2 c : group) {
            c.amount = newAmount;
        }
    }


    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }


}
